package com.swotxu.oldwebproject.web.filter;

import com.swotxu.oldwebproject.utils.SessionUtil;
import com.swotxu.oldwebproject.web.pojo.ConcurrentUser;
import com.swotxu.oldwebproject.web.pojo.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 校验用户是否登录
 *
 * @Date: 2021/3/24 0024 9:19
 * @Author: swotxu
 */
public class UserCheckFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(UserCheckFilter.class);

    private List<String> excludedUris;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String excludedUris = filterConfig.getInitParameter("excludedUris");
        log.info("excludedUris:{}", excludedUris);
        if (StringUtils.isEmpty(excludedUris)) {
            return;
        }
        this.excludedUris = Arrays.asList(excludedUris.split(";"));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String servletPath = request.getServletPath();
        log.info("servletPath:{}", servletPath);
        // 排除部分请求
        if(isExcludedUri(servletPath)){
            log.info("Excluded concurrent uri！");
            filterChain.doFilter(request, response);
            return;
        }

        HttpSession session = request.getSession(false);
        UserInfo userInfo = null;
        if(session != null){
            userInfo = (UserInfo) session.getAttribute(SessionUtil.KEY_USERINFO);
        }
        // 未登录则打回登录页
        if (userInfo == null){
            log.info("Userinfo not found in session！");
            /*WebResult webResult = new WebResult(401, "无权访问，请先登陆！", null);
            sendJsonResponse(response, JSONObject.toJSONString(webResult));*/
            response.sendRedirect( request.getContextPath() + "/login/toError");
            return;
        }
        ConcurrentUser.set(userInfo);
        filterChain.doFilter(request, response);
        ConcurrentUser.remove();
    }

    @Override
    public void destroy() {

    }

    /**
     * 校验当前请求地址是否排除
     * @param uri
     * @return
     */
    private boolean isExcludedUri(String uri) {
        if (excludedUris.isEmpty()) {
            return false;
        }
        for (String ex : excludedUris) {
            uri = uri.trim();
            ex = ex.trim();
            if (uri.toLowerCase().matches(ex.toLowerCase().replace("*",".*")))
                return true;
        }
        return false;
    }
}
